package com.hotec.PROJECT_NAME.modules.sys.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.Maps;
import com.hotec.PROJECT_NAME.component.basic.SmsConfigure;
import com.hotec.PROJECT_NAME.component.enums.SmsEnum;
import com.hotec.PROJECT_NAME.utils.UtilsEncrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@Service("trustSmsService")
public class TrustSmsService extends AbstractSmsService {
    @Autowired
    private SmsConfigure smsConfigure;

    @Override
    void postMsg(String mobile, SmsEnum type, String smsCode) {
        SmsConfigure.Trust trustConfigure = smsConfigure.getTrust();

        String url = trustConfigure.getUrl();
        String appId = trustConfigure.getAppId();
        String secret = trustConfigure.getSecret();
        String template = trustConfigure.getTemplate();

        String timestamp = DateUtil.format(new Date(), "yyyyMMddHHmmss");

        String sign = UtilsEncrypt.MD5(appId + secret + timestamp);

        LinkedHashMap<String, Object> sendParam = Maps.newLinkedHashMap();
        sendParam.put("appId", appId);
        sendParam.put("timestamp", timestamp);
        sendParam.put("sign", sign);
        sendParam.put("mobiles", mobile);
        sendParam.put("content", StrUtil.format(template, smsCode));

        String responseText = HttpUtil.get(url, sendParam);

        Map<String, Object> responseMap = JSONUtil.toBean(responseText, new TypeReference<Map<String, Object>>() {
        }, true);

        String code = MapUtil.getStr(responseMap, "code");

        Assert.isTrue(StrUtil.equalsIgnoreCase(code, "SUCCESS"), StrUtil.format("[{}]短信发送异常", code));
    }
}
